require "Common/define"
require "Logic/Config"
require "Common/functions"
---@class EmailManager
EmailManager = {};
local this = EmailManager;

local tabAllEmail = {};
local equipData = nil;
local itemData = nil;
local globalData = nil;
local heroShowTable={};
local Curmsg=nil;

function EmailManager.init()
    equipData = dataTable.getDataTable("t_equip");
    itemData = G.dataTable["t_item"];
    globalData = G.dataTable["t_global"];
end

--获取email列表
function EmailManager.getEmailList()
    local emailList = {};
    for k,v in pairs(tabAllEmail) do
        table.insert(emailList,v);
    end
    return emailList;
end
function EmailManager.GetEmail(id)
    return tabAllEmail[id]
end
function EmailManager.addEmailInfo(emailInfo, isAdd)
    local id = tostring(emailInfo.mailId);
    local item = tabAllEmail[id];
    if(item == nil) then
        item = {};
    else
        if isAdd ~= nil and isAdd then
            logError("获得一封重复的email id:"..id)
        end
        return;
    end
    item["mailId"] = id;
    item["cfgId"] = emailInfo.mailConfId
    item["mailRead"] = emailInfo.mailRead;   --是否已经阅读
    item["mailGetItems"] = emailInfo.mailGetItems;        --是否已经领取附件
    if emailInfo.attachmentPet then
        item.attachmentPet = emailInfo.attachmentPet
    end

    -- logError("没有附件的邮件mailGetItems是多少"..item["mailGetItems"])

    item["sendTime"] = tonumber(tostring(emailInfo.sendTime))/1000
    item["deadTime"] = 0
    if emailInfo.parameter then
        item.param = decodeJsonStrToTabel(emailInfo.parameter)
        local cfg = dataTable.getDataTableByStringId("t_email",item.cfgId)
        if cfg and cfg.f_Time2 > 0 then
            item["deadTime"] = tonumber(item["sendTime"]) +cfg.f_Time2 * 24*3600
        end
    end
    local senderName = tostring(emailInfo.senderName);
    if senderName ~= nil and string.sub(getLanguage(senderName), 1, 16) == "not have thisKey" then
        item["mailSubject"] = tostring(emailInfo.mailSubject);
        emailInfo.mailContent = string.gsub(emailInfo.mailContent, "\\n", "\n");
        emailInfo.mailContent = string.gsub(emailInfo.mailContent, "&quot;", "\"");
        item["mailContent"] = tostring(emailInfo.mailContent);
        item["senderName"] = string.format(getLanguage("Email_SenderTip"),tostring(emailInfo.senderName))--"发送人: "..tostring(emailInfo.senderName);
    else
        item["mailSubject"] = getLanguage(emailInfo.mailSubject);
        if item.cfgId == 101 then --X月X日-每日魔石卡
            local st = item.sendTime - 18 * 3600 --策划大佬说18点才发今天的每日奖励，so要减掉18小时
            item["mailSubject"] = string.format(item.mailSubject,tonumber(os.date("%m",st)),tonumber(os.date("%d",st)))
        end
        if item.param and item.param.param1 then
            if item.cfgId == 27 or item.cfgId == 28 or item.cfgId == 29 then --公告排行榜
                local subName = getLanguage("BillboardSubRank"..item.param.param1)
                item["mailContent"] = string.format(getLanguage(emailInfo.mailContent),subName,item.param.param2)
            else
                item["mailContent"] = string.format(getLanguage(emailInfo.mailContent),item.param.param1,item.param.param2)
            end
        else
            item["mailContent"] = getLanguage(emailInfo.mailContent)
        end

        item["senderName"] = string.format(getLanguage("Email_SenderTip"),getLanguage(senderName))
    end
    item["rewards"] = {};
    if #emailInfo.mailItems ~= 0 then
        for j = 1 , #emailInfo.mailItems do
            local rewardInfo = {};
            local itemModelId = tostring(emailInfo.mailItems[j].itemModelId);
            rewardInfo["itemModelId"] = itemModelId;
            rewardInfo["quality"] = tostring(emailInfo.mailItems[j].quality);
            rewardInfo["isbind"] = emailInfo.mailItems[j].isbind;
            rewardInfo["ltime"] = emailInfo.mailItems[j].ltime;
            rewardInfo["parameters"] = emailInfo.mailItems[j].parameters;
            rewardInfo["num"] = emailInfo.mailItems[j].num;

            if logicMgr.ItemManager.IsEquip(itemModelId) then
                rewardInfo["icon"] = equipData[itemModelId].f_EquipIcon;
                rewardInfo["name"] = getLanguage(equipData[itemModelId].f_EquipName);
                rewardInfo["desc"] = getLanguage(equipData[itemModelId].f_EquipDesc);
                rewardInfo["itemType"] = equipData[itemModelId].f_EquipType;
            else
                local d = itemData[itemModelId]
                if d then
                    rewardInfo["icon"] = d.f_Icon;
                    rewardInfo["name"] = getLanguage(d.f_ItemName);
                    rewardInfo["desc"] = getLanguage(d.f_Desc);
                    rewardInfo["itemType"] = d.f_BagType;
                else
                    logError("[邮件]can not find item in config by id:"..itemModelId)
                end
            end
            table.insert(item["rewards"],rewardInfo);
        end

        local modelId = tostring(emailInfo.mailItems[1].itemModelId);
        if logicMgr.ItemManager.IsEquip(modelId) then
            item["icon"] = equipData[modelId].f_EquipIcon;
            item["quality"] = equipData[modelId].f_EquipQuality;
        else
            if itemData[modelId] then
                item["icon"] = itemData[modelId].f_Icon;
                item["quality"] = itemData[modelId].f_Quality;
            end
        end
    else
        item["icon"] = globalData[tostring(68)].f_int_value;
        --没有附件的情况下,标记已领取，一键删除时用到
        --item["mailGetItems"] = 1;        --是否已经领取附件
    end

    this.setEmailStatue(item);
    tabAllEmail[item.mailId] = item;
    --print("========================>")
    --dataTable.PrintTable(tabAllEmail)

end
function EmailManager.UpdateEmailRewardAllState()
    for k,v in pairs(tabAllEmail) do
        this.updateEmailRewardState(v.mailId,true)
    end
end
function EmailManager.IsOutDate(mailId)
    local mail = tabAllEmail[mailId]
    if not mail == nil then return false end
    return mail.deadTime > 0 and HelperFunc.GetServerTime() >= mail.deadTime
end

--通知奖励领取状态  暂定1 为领取
function EmailManager.updateEmailRewardState(emailId,checkDeadTime)
    local mail = tabAllEmail[emailId]
    if(mail ~= nil) then
        mail["mailRead"] = 1;
        if mail.deadTime >  0 and checkDeadTime and HelperFunc.GetServerTime()>= mail.deadTime then
            --过期
        else
            mail["mailGetItems"] = 1;
        end
        this.setEmailStatue(mail);
        -- 领取邮件奖励后埋点
        local _emailAwardDic = {}
        _emailAwardDic.email_id = tostring(emailId)
        _emailAwardDic.email_config_id = tostring(mail["cfgId"])
        TAManager.TrackByDictionary("email_award",_emailAwardDic)
        for i = 1, #mail["rewards"]  do
            if mail["rewards"][i]["itemType"] == 4096 then
                local _partnerModelId= tostring(mail["rewards"][i]["itemModelId"]-201500);
                local heroData = logicMgr.HeroManager.getHeroDatabyModelId(_partnerModelId,true);
                if heroData ~= nil and heroData.isNew then   
                    table.insert(heroShowTable,heroData);
                    logicMgr.HeroManager.setHeroIsNew(heroData.partnerId, false)   
                end
               
            end
        end
    end
end

function EmailManager.SetMsg(msg)
    Curmsg=msg;
end
function EmailManager.showAllNewHero()
    if #heroShowTable > 0 then
        this.showOneNewHero(this.showAllNewHero);
    else
        DestoryUI(PanelNames.UIDrawAnimation);
        FireEvent(Config.EventType.GetEmailRewardTip,Curmsg.addItems,Curmsg.mailIdList) --一键领取需要先取状态
        FireEvent(Config.EventType.Fresh_Email);
    end
end

function EmailManager.showOneNewHero(Callback)  

    if #heroShowTable > 0 then
        showUI(PanelNames.UIDrawAnimation, heroShowTable[1].partnerModelId, nil, false,Callback,
        nil, true);     
        table.remove(heroShowTable, 1);
    else
        if Callback then
            Callback();
        end
    end
    
end


function EmailManager.DeleteAll()
    for k,v in pairs(tabAllEmail) do
        if v.mailRead ~= 0 and  v["mailGetItems"] ~= 0 or logicMgr.EmailManager.IsOutDate(v.mailId) then
            emailHandler.reqDeleteMail(emailDatalist[i]["mailId"]);
        end
    end
end
--通知邮件删除
function EmailManager.deleteEmail(emailId)
    local mail = tabAllEmail[emailId]
    if(mail ~= nil) then
        tabAllEmail[emailId] = nil
    end
end

--通知邮件已读
function EmailManager.readEmail(emailId)
    local mail = tabAllEmail[emailId]
    if(mail ~= nil) then
        mail["mailRead"] = 1;
        this.setEmailStatue(mail);
        --阅读邮件
        local _emailDic = {}
        _emailDic.email_id = tostring(emailId)
        _emailDic.email_sender = tostring(mail["senderName"])
        _emailDic.email_source = -1
        TAManager.TrackByDictionary("email_read",_emailDic)
    end
end

--设置邮件状态
function EmailManager.setEmailStatue(mail)
    local mailStatue = 0;
    mailStatue = tonumber(mail["mailRead"]);
    if mailStatue == 1 then
        local haveReward = mail["rewards"] ~= nil and #mail["rewards"] > 0
        if mail["mailGetItems"] == 0 and haveReward then
            mailStatue = 0;

        end
    end
    mail["mailStatue"] = mailStatue;
end

return EmailManager